local app = require "app"
local game = require "club.threecard.sudoku"
local AvatarIcon = require "ui.Common.AvatarIcon"

local M = game.ui.activity()

local function extract_opponent_player(versus)
    local my_user_id = game.kbe.player().user_id
    local players = versus.players
    for _, player in ipairs(players) do
        if my_user_id ~= player.user_id then
            return player
        end
    end
end

function M:ctor(versus)
    self.res = "club.threecard.sudoku/ui/versus.b:NewOpponentUI"
    self.versus = versus
    self.icon = AvatarIcon.new()
    self.player = extract_opponent_player(versus)
end

function M:on_load()
    self:super("on_load")
    self:set_layer(app.config.ui.layout.top.layer)
end

function M:on_injected(bind)
    bind("gameobject.element", self.icon_obj, self.icon)
    bind("button.click", self.accept_btn, self.on_accept)
    bind("button.click", self.cancel_btn, self.on_cancel)
    self.icon:set_player(self.player)
    self.name_txt.text = self.player.nickname
end

function M:set_versus(versus)
    self.versus = versus
    self.player = extract_opponent_player(versus)
    self.icon:set_player(self.player)
    self.name_txt.text = self.player.nickname
end

function M:on_accept()
    game.audio.post("click")
    game.router.push("/club.threecard.sudoku/versus-detail/" .. self.versus.id)
    self:hide()
end

function M:on_cancel()
    game.audio.post("click")
    self:hide()
end

return M